package com.app.view;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.view.View;

import com.app.util.Utils_Log;

/**
 * 用于秒杀的倒计时模块
 * @author Administrator
 *
 */
public class TimeCountDownView extends View{

	private String TAG = "TimeCountDownView";
	
	
	private Context mContext;
	
	
	private Paint paint_black = new Paint();
	private Paint paint_gray = new Paint();
	private Paint paint_gray555 = new Paint();
	private Paint paint_orange = new Paint();
	private Paint paint_white = new Paint();
	
	private Point point_start = new Point();
	private Point point_end = new Point();
	
	
	Rect RectHourHigh = new Rect();
	Rect RectHourLow = new Rect();
	Rect RectMinuteHigh = new Rect();
	Rect RectMinuteLow = new Rect();
	Rect RectSecondHigh = new Rect();
	Rect RectSecondLow = new Rect();
	Rect RectTimeSpaceHM = new Rect();
	Rect RectTimeSpaceMS = new Rect();
	
	
	
	long mTotalTime ;		// 
	long mMillisUntilFinished ;
	String mUserSetTime = "";
	String[] mResultTime ;
	
	
	//  
	CountDownTimer mCountDownTimer;
	
	
	OnListener mListener;
	
	
	
	private int width_measure ;
	private int height_measure ;
	
	
	
	
	public TimeCountDownView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		
		this.mContext = context;
		
		
		
		/*OK, 接受自定义属性
        if (null != attrs) {
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TimeCountDownView);

            if (ta != null) {
            	
            	mUserSetTime = ta.getString(R.styleable.TimeCountDownView_time);
                ta.recycle();
            }
        }
        else{
        	mUserSetTime = "0:0:11";  // 
        	
        }
		*/
        
        if( !isInEditMode() )
        {
	        mTotalTime = GetDeltaTime(mUserSetTime);
	        Utils_Log.i(TAG, "mUserSetTime: "+mUserSetTime);
	        Utils_Log.i(TAG, "mTotalTime: "+mTotalTime);
        }
        
	
		
		point_start.x = 1;
		point_start.y = 1;
       
		
		paint_black.setColor( getResources().getColor(android.R.color.black));
		paint_gray.setColor( getResources().getColor(android.R.color.darker_gray));
		paint_gray555.setColor( Color.parseColor("#555555"));
		paint_orange.setColor( getResources().getColor(android.R.color.holo_orange_light));
		paint_white.setColor( getResources().getColor(android.R.color.white) );
		
		
    	/*
    //	mUserSetTime = "11:11:11";
    	SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss" , Locale.getDefault());
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    	Date date = new Date(mTotalTime * 1000);
    	mUserSetTime = sdf.format(date);
    	*/
  //   	mUserSetTime = DateFormat.format("hh:mm:ss", mTotalTime-8*60*60*1000 ).toString(); //会多出8个小时 	
    
    	
    	/*
    	mCountDownTimer = new CountDownTimer(mTotalTime, 1000) {
    		
    		@Override
    		public void onTick(long millisUntilFinished) {
    			// TODO Auto-generated method stub
    			
    			Utils_Log.i(TAG, "onTick: "+millisUntilFinished);
    			
    			//
    			if(mListener != null)
    				mListener.OnProgress(millisUntilFinished);
    			
    			mMillisUntilFinished = millisUntilFinished;
    			invalidate();
    		}
    		
    		@Override
    		public void onFinish() {
    			// TODO Auto-generated method stub
    			Utils_Log.i(TAG, "onFinish");
    			
    			
    			mMillisUntilFinished = 0;
    			invalidate();
    			
    			if(mListener != null)
    				mListener.OnComplete();
    	//		Utils1.showToastShort(mContext, "开始秒杀~");
    			
    		}
    	};
    	mCountDownTimer.start();
    	*/
    	
    	//
    //	if(mListener != null)
    //		mListener.OnStart();
    	
	}
	
	
	///* 将毫秒转换成时间格式
	// http://www.eoeandroid.com/thread-318614-1-1.html
	public static String GetSeparateTime(long TotalTime) {
		int mss = (int)TotalTime;
        int hours = (mss / (1000 * 60 * 60));  
        int minutes = (mss - hours * (1000 * 60 * 60)) / (1000 * 60);  
        int seconds = (mss - hours * (1000 * 60 * 60) - minutes * (1000 * 60)) / 1000;  
        
        String str_hours = ""+hours;
        String str_minutes = ""+minutes;
        String str_seconds = ""+seconds;
        if(str_hours.length()!=2){
        	str_hours = "0"+str_hours;
        }
        if(str_minutes.length() != 2){
        	str_minutes = "0"+str_minutes;
        }
        if(str_seconds.length() != 2){
        	str_seconds = "0"+str_seconds;
        }
        
        return  str_hours + ":" + str_minutes + ":"  
                + str_seconds ;  
    }
	
	// 将格式时间转换成毫秒
	public static long GetDeltaTime(String str_time){
		long DeltaTime = 0;
		
		String[] time = str_time.split(":");
		if(time.length < 3)
			return 0;
		
		int hours = Integer.valueOf(time[0]);
		int minutes = Integer.valueOf(time[1]);
		int seconds = Integer.valueOf(time[2]);
	
		
		DeltaTime = hours*60*60*1000 + minutes*60*1000 + seconds*1000;
		
		return DeltaTime;
		
	}
	//*/
	
	
	
	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		// TODO Auto-generated method stub
		super.onLayout(changed, left, top, right, bottom);
		
		
		int TimeSpace= 20;
		
		
		int BlockWidth = 50;
		int BlockHeight = 100;
		
		
		// 转换成当前需要的格式
		

		point_start.x = 1;
		point_start.y = 1;
		
		
		// 小时
		RectHourHigh.left = point_start.x;
		RectHourHigh.top = point_start.y;
		RectHourHigh.right = RectHourHigh.left + BlockWidth;
		RectHourHigh.bottom = RectHourHigh.top + BlockHeight;
		
		point_start.x = RectHourHigh.right + 5;
		
		RectHourLow.left = point_start.x;
		RectHourLow.top = point_start.y;
		RectHourLow.right = RectHourLow.left + BlockWidth;
		RectHourLow.bottom = RectHourLow.top + BlockHeight;
		
		// time space rect
		RectTimeSpaceHM.left = RectHourLow.right;
		RectTimeSpaceHM.top = RectHourLow.top;
		RectTimeSpaceHM.right = RectTimeSpaceHM.left + TimeSpace;
		RectTimeSpaceHM.bottom = RectHourLow.bottom;
		//
		point_start.x = RectHourLow.right + TimeSpace;
		
		// 分钟
		RectMinuteHigh.left = point_start.x;
		RectMinuteHigh.top = point_start.y;
		RectMinuteHigh.right = RectMinuteHigh.left + BlockWidth;
		RectMinuteHigh.bottom = RectMinuteHigh.top + BlockHeight;
		
		point_start.x = RectMinuteHigh.right + 5;
		
		RectMinuteLow.left = point_start.x; 
		RectMinuteLow.top = point_start.y;
		RectMinuteLow.right = RectMinuteLow.left + BlockWidth;
		RectMinuteLow.bottom = RectMinuteLow.top + BlockHeight;
		
		
		// time space rect
		RectTimeSpaceMS.left = RectMinuteLow.right;
		RectTimeSpaceMS.top = RectMinuteLow.top;
		RectTimeSpaceMS.right = RectTimeSpaceMS.left + TimeSpace;
		RectTimeSpaceMS.bottom = RectMinuteLow.bottom;
		//
		point_start.x = RectMinuteLow.right + TimeSpace;
		
		
		// 秒
		RectSecondHigh.left = point_start.x;
		RectSecondHigh.top = point_start.y;
		RectSecondHigh.right = RectSecondHigh.left + BlockWidth;
		RectSecondHigh.bottom = RectSecondHigh.top + BlockHeight;
		
		point_start.x = RectSecondHigh.right + 5;
		
		RectSecondLow.left = point_start.x;	
		RectSecondLow.top = point_start.y;
		RectSecondLow.right = RectSecondLow.left + BlockWidth;
		RectSecondLow.bottom = RectSecondLow.top + BlockHeight;
		
		
		width_measure = point_start.x + RectSecondLow.width() + 5;
		height_measure = RectSecondLow.height();
		
	}
	
	
	
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		
  
		
		canvas.drawRect(RectHourHigh, paint_gray555);
		canvas.drawRect(RectHourLow, paint_gray555);
			new TimeSpace().show(canvas, RectTimeSpaceHM);
	//		canvas.drawRect(RectTimeSpaceHM, paint_orange);
		canvas.drawRect(RectMinuteHigh, paint_gray555);
		canvas.drawRect(RectMinuteLow, paint_gray555);
			new TimeSpace().show(canvas, RectTimeSpaceMS);
	//		canvas.drawRect(RectTimeSpaceMS, paint_orange);
		canvas.drawRect(RectSecondHigh, paint_gray555);
		canvas.drawRect(RectSecondLow, paint_gray555);
		
		
		String[] time = GetSeparateTime(mMillisUntilFinished).split(":");
		if(time.length < 3){
			Utils_Log.i(TAG, "时间数组长度不够: "+time);
			return ;
		}
		
		
		paint_white.setTextSize(50);
		
		/* ok
		float[] widths = new float[1];
		paint_white.getTextWidths("0", widths);
		float width = widths[0];
		*/
		
		Rect bounds = new Rect();
		paint_white.getTextBounds("012345", 0, 1, bounds);
		float width = bounds.width()/2;
		float height = bounds.height()/2; 
		
		// 计算文字长度
		// paint_white.measureText(text);
		
		
		//
		// 文字的输出，y表示的是文字的底部坐标; 因此是,TextY = CenterY + half_text_height;这样文字才输出到目标的中央;
		// 
		
		// 小时
		String str_HourHigh =time[0].substring(0,1);
		String str_HourLow = time[0].substring(1);
		canvas.drawText(str_HourHigh, RectHourHigh.centerX()-width, RectHourHigh.centerY()+height, paint_white);
		canvas.drawText(str_HourLow, RectHourLow.centerX()-width, RectHourLow.centerY()+height, paint_white);
		
		
		// 分钟
		String str_MinuHigh =time[1].substring(0,1);
		String str_MinuLow = time[1].substring(1);
		canvas.drawText(str_MinuHigh, RectMinuteHigh.centerX()-width, RectMinuteHigh.centerY()+height, paint_white);
		canvas.drawText(str_MinuLow, RectMinuteLow.centerX()-width, RectMinuteLow.centerY()+height, paint_white);
		
		// 秒
		String str_SecondHigh =time[2].substring(0,1);
		String str_SecondLow = time[2].substring(1);
		canvas.drawText(str_SecondHigh, RectSecondHigh.centerX()-width, RectSecondHigh.centerY()+height, paint_white);
		canvas.drawText(str_SecondLow, RectSecondLow.centerX()-width, RectSecondLow.centerY()+height, paint_white);
		

		
		
		
		
	}


	public void SetOnListener(OnListener Listener){
		mListener = Listener;
	}
	
	
	// 
	/**
	 * 设置倒计时，形如"0:0:0"
	 * @param UserSetTime
	 */
	public void Start(String UserSetTime){
		
		mUserSetTime = UserSetTime;
		mTotalTime = GetDeltaTime(mUserSetTime);

		
		if(mCountDownTimer != null)	
			mCountDownTimer.cancel();
		
		
    	mCountDownTimer = new CountDownTimer(mTotalTime, 1000) {
    		
    		@Override
    		public void onTick(long millisUntilFinished) {
    			// TODO Auto-generated method stub
    			
    			Utils_Log.i(TAG, "onTick: "+millisUntilFinished);
    			
    			//
    			if(mListener != null)
    				mListener.OnProgress(millisUntilFinished);
    			
    			mMillisUntilFinished = millisUntilFinished;
    			invalidate();
    		}
    		
    		@Override
    		public void onFinish() {
    			// TODO Auto-generated method stub
    			Utils_Log.i(TAG, "onFinish");
    			
    			
    			mMillisUntilFinished = 0;
    			invalidate();
    			
    			if(mListener != null)
    				mListener.OnComplete();
    	//		Utils1.showToastShort(mContext, "开始秒杀~");
    			
    		
    		}
    	};
    	mCountDownTimer.start();
    	
		
	}
	
	
	
	
	
	
	
	// 倒计时状态监听器
	public interface OnListener{
	//	public void OnStart();
		public void OnProgress(long millisUntilFinished);
		public void OnComplete();
	}
	
///////////////////////////////////////////////////////////////////////////////////
	
	/**
     * @see android.view.View#measure(int, int)
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureWidth(widthMeasureSpec),
                measureHeight(heightMeasureSpec));
    }

    /**
     * Determines the width of this view
     * @param measureSpec A measureSpec packed into an int
     * @return The width of the view, honoring constraints from measureSpec
     */
    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            // We were told how big to be
            result = specSize;
        } else {

        	result += getPaddingLeft() + getPaddingRight();
        	result +=width_measure;
            if (specMode == MeasureSpec.AT_MOST) {
                // Respect AT_MOST value if that was what is called for by measureSpec
                result = Math.min(result, specSize);
            }
        }

        return result;
    }

    /**
     * Determines the height of this view
     * @param measureSpec A measureSpec packed into an int
     * @return The height of the view, honoring constraints from measureSpec
     */
    private int measureHeight(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            // We were told how big to be
            result = specSize;
        } else {
        	result += getPaddingTop() + getPaddingBottom();
        	result += height_measure;
            if (specMode == MeasureSpec.AT_MOST) {
                // Respect AT_MOST value if that was what is called for by measureSpec
                result = Math.min(result, specSize);
            }
        }
        return result;
    }
    
	
	

}



